package com.briup.product_source.service.Impl;

import com.briup.product_source.bean.Basic.Animal;
import com.briup.product_source.bean.Basic.MangerQRCode;
import com.briup.product_source.bean.Ext.AnimalExt;
import com.briup.product_source.bean.Ext.ManagerAnimalExt;
import com.briup.product_source.dao.Basic.MangerQRCodeMapper;
import com.briup.product_source.dao.Ext.AnimalExtMapper;
import com.briup.product_source.service.AnimalService;
import com.briup.product_source.util.Assert;
import com.briup.product_source.util.OSSUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.briup.product_source.util.ResultCode.*;


@Service
public class AnimalServiceImpl implements AnimalService {
    @Value("${QRcode.host}")
    private String QRcodeHost;
    @Autowired
    private AnimalExtMapper animalExtMapper;
    @Value("${qiniuyun.uri}")
    private String host;
    @Autowired
    private OSSUtil ossUtil;
    @Autowired
    private MangerQRCodeMapper qrCodeMapper;

    @Override
    public void saveOrUpdate(@RequestBody Animal animal) {
        String aId = animal.getaAnimalId();
        if (aId == null || "".equals(aId.trim())) {
            //新增
            String id = UUID.randomUUID().toString().replace("-", "");
            animal.setaAnimalId(id);
            if (animal.getaTime() != null) {
                animal.setaTime(new Date());
            }
            animalExtMapper.insertSelective(animal);
        } else {
            Assert.isNull(animalExtMapper.selectByPrimaryKey(aId), ANIMAL_NULL);
            animalExtMapper.updateByPrimaryKey(animal);
        }

    }


    @Override
    public void deleteById(String id) {
        Animal animal = animalExtMapper.selectByPrimaryKey(id);
        Assert.isNull(animal, ANIMAL_NULL);
        animalExtMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteById(List<String> ids) {
        animalExtMapper.deleteByIds(ids);
    }

    @Override
    public PageInfo<AnimalExt> findByPage(Integer pageNum, int pageSize, String aHealthy, String aGender) {
        PageHelper.startPage(pageNum, pageSize, true);
        List<AnimalExt> list = animalExtMapper.selectByPage(aHealthy, aGender);
        list.stream().forEach(animal -> {
            animal.setUrl(String.join("/", host, animal.getUrl()));
        });
        return new PageInfo<>(list);
    }

    @Override
    public ManagerAnimalExt findById(String id) {
        ManagerAnimalExt managerAnimalExt = animalExtMapper.findAnimalById(id);
        Assert.isNull(managerAnimalExt, ANIMAL_NULL);
        return managerAnimalExt;
    }

    @Override
    public String createQRcodeByAnimalId(String id) {
        String content = QRcodeHost+"/animal/findByAnimalId?animalId="+id; // 要编码到二维码中的内容
        int width = 300; // 二维码图片宽度
        int height = 300; // 二维码图片高度
        String fileName = "qr.png";
        try {
            //表示二维码信息
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);

            //将二维码信息(图片字节信息)写到指定输出流out
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", out);

            //将图片的字节信息保存到oss
            InputStream in = new ByteArrayInputStream(out.toByteArray());
            String path = ossUtil.upload(fileName, in);
            //将二维码的路径保存在数据库中
            //如果不重复，进行新增
            MangerQRCode qRcode = new MangerQRCode();
            qRcode.setqAnimalId(id);
            qRcode.setqImageUrl(path);
            qrCodeMapper.insertSelective(qRcode);
            return path;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
